<%@ include file="_header.jspf" %>
<%@ page import="com.spartancoder.accommodation.models.AuthToken" %>
<%@ page import="com.spartancoder.accommodation.models.Administrator" %>
<%@ page import="com.spartancoder.accommodation.beans.AdministratorBean" %>
<%@ page import="com.spartancoder.accommodation.models.AccommodationSession" %>
<%@ page import="com.spartancoder.accommodation.models.Student" %>
<%@ page import="com.spartancoder.accommodation.beans.StudentBean" %>
<%@ page import="com.spartancoder.accommodation.beans.AccommodationSessionBean" %>
<%

AuthToken authToken = (AuthToken)request.getAttribute("authToken");
if( authToken.isStudent() ) {
    response.sendRedirect("student/index.jsp");
} else if( authToken.isAdmin() ) {
    response.sendRedirect("admin/index.jsp");
}

String user = request.getParameter("user");
String password = request.getParameter("password");
String error = null;

if ( user != null && password != null ) {
    if( user.length() == 13 ) {
        StudentBean sb = Student.fetch(user, password);
        if( sb == null ) {
            error = "Utilizator negasit sau parola invalida";
        } else {
            AccommodationSessionBean ab = AccommodationSession.fetchActive();
            if(ab == null) {
                session.setAttribute("flash", "Nu exista o sesiune de cazare activa.");
                response.sendRedirect("index.jsp");
            } else {
                authToken.setStudent(sb.getStudentId());
                response.sendRedirect("student/index.jsp");
            }
        }
    } else {
        AdministratorBean ab = Administrator.fetch(user, password);
        if( ab == null ) {
            error = "Utilizator negasit sau parola invalida";
        } else {
            authToken.setAdministrator(ab.getAdministratorId());
            response.sendRedirect("admin/index.jsp");
        }
    }
} else {
    user = "";
    password = "";
}
%>

<div class="content span-10">
    <form action="login.jsp" method="post">
        <fieldset>
            <% if(error != null) { 
                %><br /><div class="error"><%=error%></div><%
            } %>
            <label class="large">User or CNP:</label><br />
            <input type="text" name="user" class="text large" value="<%=user%>" /><br />
            
            <label class="large">Password</label><br />
            <input type="password" name="password" class="text large" value="<%=password%>" /><br />
            
            <button type="submit" class="button positive">
                <img src="images/icons/tick.png" />
            Login</button>
        </fieldset>
    </form>
</div>

<%@ include file="_footer.jspf" %>